import SwiftUI
import RealityKit // 需要 Transform

// 定义不同的应用屏幕/状态
enum AppScreen {
    case splash1
    case splash2
    case mainMenu
    case factorySelection
    // Immersive 状态由是否打开 ImmersiveSpace 隐式管理
}

// 定义当前显示的 3D 模型类型
enum ModelDisplayType: Equatable {
    case none
    case generic // 用于主菜单按钮 3 (如果需要)
    case factory(name: String)
    case internalModel(factoryName: String)
    case workstation(factoryName: String, workstationName: String)

    var modelName: String? {
        switch self {
        case .none: return nil
        case .generic: return "DefaultObject" // 示例名称
        case .factory(let name): return "Plant2.usd"
        case .internalModel(let factoryName): return "\(factoryName)_Internal" // 假设的命名约定
        case .workstation(let factoryName, let workstationName): return "\(factoryName)_\(workstationName)" // 假设的命名约定
        }
    }
}

@MainActor // 确保所有 @Published 属性的更新都在主线程上
class AppState: ObservableObject {
    // --- Navigation State ---
    @Published var currentScreen: AppScreen = .splash1
    @Published var showingSafetyAlert: Bool = false

    // --- Immersive Space State ---
    let immersiveSpaceID = "FactoryDetailSpace" // ImmersiveSpace 的 ID
    @Published var currentModelType: ModelDisplayType = .none
    @Published var isImmersiveSpaceShown: Bool = false // 跟踪空间是否已打开

    // --- Model Interaction State ---
    @Published var modelEntity: ModelEntity? = nil // 当前加载的模型实体
    @Published var rootEntity = Entity()        // 用于应用变换的根实体
    @Published var modelTransform: Transform = Transform.identity // 当前变换
    @Published var initialModelTransform: Transform = Transform.identity // 初始变换（用于重置）
    @Published var isRoofLifted: Bool = false

    // 用于手势交互的状态
    var startScale: Float = 1.0
    var startRotation: simd_quatf = simd_quatf() // 四元数表示旋转

    // --- Factory Data ---
    let factoryNames = ["RBCD", "RBCW", "ME", "PT", "RBCC", "CC"]

    // --- Methods ---

    func selectFactory(_ name: String) {
        print("Selected factory: \(name)")
        currentModelType = .factory(name: name)
        resetModelStateForNewLoad() // 重置状态以加载新模型
        // 触发 ImmersiveSpace 的打开将在视图中处理
    }

    func showInternalModel() {
        guard case .factory(let name) = currentModelType else { return }
        print("Showing internal model for: \(name)")
        currentModelType = .internalModel(factoryName: name)
        resetModelStateForNewLoad()
    }

    func showWorkstation(_ workstationName: String) {
        // 需要从当前状态推断出 factoryName
        let factoryName: String
        switch currentModelType {
        case .internalModel(let fName):
            factoryName = fName
        case .workstation(let fName, _): // 如果已经在工作站视图，也允许切换
             factoryName = fName
        default:
            print("Error: Cannot determine factory name for workstation.")
            return
        }
        print("Showing workstation: \(workstationName) in factory: \(factoryName)")
        currentModelType = .workstation(factoryName: factoryName, workstationName: workstationName)
        resetModelStateForNewLoad()
    }

    // 用于在加载新模型前重置相关状态
    func resetModelStateForNewLoad() {
        isRoofLifted = false
        modelEntity = nil // 清除旧模型
        // rootEntity 不需要每次都重新创建，但其内容会被替换
        modelTransform = Transform.identity
        initialModelTransform = Transform.identity
        startScale = 1.0
        startRotation = simd_quatf()
        // 注意：modelEntity 的加载将在 ImmersiveFactoryView 的 make/update 中进行
    }


    func handleTapOnRoof() {
         guard case .factory = currentModelType, modelEntity != nil else { return } // 仅工厂模型有屋顶操作
         withAnimation(.easeInOut(duration: 0.7)) { // 添加动画
             isRoofLifted.toggle()
             print("Roof lifted state: \(isRoofLifted)")
         }
     }

    func goBack() {
        print("Go back triggered. Current type: \(currentModelType), Roof lifted: \(isRoofLifted)")
        if isRoofLifted {
            // 如果屋顶升起，优先降下屋顶
            withAnimation(.easeInOut(duration: 0.7)) {
                isRoofLifted = false
            }
            print("Lowering roof.")
        } else {
            // 根据当前模型类型决定返回逻辑
            switch currentModelType {
            case .workstation(let factoryName, _):
                print("Returning from Workstation to Internal Model")
                showInternalModel() // 返回到内部模型
            case .internalModel(let factoryName):
                 print("Returning from Internal Model to Factory")
                // 需要重新设置模型类型为工厂，但不自动打开沉浸空间
                currentModelType = .factory(name: factoryName)
                 resetModelStateForNewLoad()
                // Immersive view 会检测到 currentModelType 变化并重新加载工厂模型

            case .factory:
                print("Returning from Factory to Factory Selection")
                // 从工厂模型返回，意味着关闭沉浸空间并返回选择界面
                 currentModelType = .none
                 isImmersiveSpaceShown = false // 触发关闭
                 currentScreen = .factorySelection // 更新主窗口状态
            case .generic, .none:
                 // 从其他状态返回，可能需要关闭沉浸空间并返回主菜单
                 currentModelType = .none
                 isImmersiveSpaceShown = false
                 currentScreen = .mainMenu
            }
        }
    }

    func goToMainMenu() {
        print("Going to Main Menu")
        currentModelType = .none
        isImmersiveSpaceShown = false // 触发关闭
        currentScreen = .mainMenu
    }

    func resetModelTransform() {
        print("Resetting model transform")
        modelTransform = initialModelTransform
        // 同时重置手势的起始状态，以便下次手势从初始状态开始
        startScale = initialModelTransform.scale.x // 假设统一缩放
        startRotation = initialModelTransform.rotation
    }
}
